<!DOCTYPE html>
<html>

<head>
    <title>调用摄像头并发送视频流</title>
</head>

<body>
    <video id="localVideo" autoplay playsinline></video>
    <button id="startButton">开始</button>
    <button id="stopButton" disabled>停止</button>

    <script>
        const localVideo = document.getElementById('localVideo');
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');

        let mediaStream;
        let mediaRecorder;
        let chunks = [];

        startButton.addEventListener('click', async () => {
            try {
                mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                localVideo.srcObject = mediaStream;

                mediaRecorder = new MediaRecorder(mediaStream);
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        chunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = () => {
                    const blob = new Blob(chunks, { type: 'video/webm' });
                    const formData = new FormData();
                    formData.append('video', blob, 'recorded.webm');

                    // 将视频流发送到服务器
                    fetch('http://your_server_url/upload', {
                        method: 'POST',
                        body: formData
                    }).then(response => {
                        console.log('视频流已发送到服务器');
                    }).catch(error => {
                        console.error('发送视频流失败:', error);
                    });
                };

                mediaRecorder.start();
                startButton.disabled = true;
                stopButton.disabled = false;
            } catch (error) {
                console.error('获取摄像头失败:', error);
            }
        });

        stopButton.addEventListener('click', () => {
            mediaRecorder.stop();
            mediaStream.getTracks().forEach(track => track.stop());
            localVideo.srcObject = null;
            startButton.disabled = false;
            stopButton.disabled = true;
        });
    </script>
</body>

</html>